/*
 * Copyright 2007 National Bioinformatics Network
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package dgbgui.tools;

import java.awt.FileDialog;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;

import dgbgui.DGBGUI;
import dgbgui.logging.ErrorLogger;
import dgbgui.modeldocument.ModelDocument;
import dgbgui.modeldocument.ModelDrivenWorkspace;
import dgbgui.modeldocument.ResultStore;

public class LoadTool implements Tool {

    public void execute() {
        
        FileDialog dialog = new FileDialog(DGBGUI.getInstance().getMainFrame(),"LOAD",FileDialog.LOAD);
        dialog.setFilenameFilter(new ModelFileFilter("dgm"));
        
        DGBGUI.centerDialog(dialog);
        dialog.setVisible(true);
        String fileName = null;
        if ( dialog.getFile() != null ) {
            fileName = dialog.getDirectory() + dialog.getFile();
        }
        
        if ( fileName != null ) {
            try {
                ObjectInputStream stream = null;
                try {
                    stream = new ObjectInputStream(
                            new BufferedInputStream(
                                    new FileInputStream(fileName)));
                    
                    
                    // Clear all
                    ClearModelTool clearTool = new ClearModelTool();
                    clearTool.execute();

                    // Stream the model document, md workspace and result store
                    ResultStore.getInstance().readFromStream(stream);
                    ModelDocument.getInstance().readFromStream(stream);
                    ModelDrivenWorkspace.getInstance().readFromStream(stream);
                    
                    // Set the filename of the model
                    ModelDocument.getInstance().setFileName(fileName);

                } catch (ClassNotFoundException e) {
                    ErrorLogger.getInstance().logString("Couldn't find class in " + fileName);
                } catch (FileNotFoundException e) {
                    ErrorLogger.getInstance().logString("Couldn't find file " + fileName + " for reading.");
                }
                if ( stream != null ) {
                    stream.close();
                }
            } catch (IOException e) {
                ErrorLogger.getInstance().logException(e);
            }
        }

    }

}
